package com.adopapa.ethexplorer.service;

import java.time.Instant;
import java.util.Base64;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Hash;

import com.adopapa.ethexplorer.domain.UserInfo;
import com.adopapa.ethexplorer.domain.UserInfo.UserType;
import com.adopapa.ethexplorer.domain.WalletInfo;
import com.adopapa.ethexplorer.utils.Tools;

@Service
public class DataSystemService extends BaseService {

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private WalletInfoService walletInfoService;

	@PostConstruct
	public void init() {
		try {

			UserInfo superadmin = userInfoService.getUserInfoByLoginName("sadmin");
			if (!Tools.empty(superadmin)) {
				return;
			}

			Map<String, String> walletMap = WalletManager.createStandardWallet("happy@1234567");
			WalletInfo walletInfo = new WalletInfo().address(walletMap.get("address")).alias("HappyEveryday")
					.keystore(walletMap.get("keystore")).createTime(Instant.now())
					.password(Base64.getEncoder().encodeToString("happy@1234567".getBytes()));

			UserInfo userInfo = new UserInfo().createTime(Instant.now()).loginName("sadmin")//
					.loginPwd(Hash.sm3("happy@1234567")).note("super admin")//
					.updateTime(Instant.now()).userName("sadmin")//
					.userType(UserType.SUPERADMIN).walletInfo(walletInfo);

			this.newUserInfo(userInfo);

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

	}

	@Transactional
	public UserInfo newUserInfo(UserInfo userInfo) {
		if (!Tools.empty(userInfo.getWalletInfo())) {
			walletInfoService.saveWalletInfo(userInfo.getWalletInfo());
		}
		return userInfoService.saveUserInfo(userInfo);
	}

}
